import AbstractCache from "./AbstractCache";
import CacheObj from "./CacheObj";

export default class LFUCache<K,V> extends AbstractCache<K, V> {

    constructor(capacity:number,timeout:number) {
        super(capacity,timeout,true);
    }

    protected pruneCache(): number {
        cc.log("满了回收")
        let count:number = 0
        let comin:CacheObj<K, V>|null = null
        cc.log(this.cacheMap.values())
        for (let value of this.cacheMap.values()) {
            if (value.isExpired()) {
                cc.log(value.getValue())
                cc.find('Canvas').removeChild(value.getValue())
                value.getValue().decRef()
                cc.assetManager.releaseAsset(value.getValue())
                this.cacheMap.delete(value.getKey());
                count++;
                continue;
            }
            //找出访问最少的对象
            if (comin == null || value.accessCount < comin.accessCount) {
                comin = value;
            }
        }
        // 减少所有对象访问量，并清除减少后为0的访问对象
        if (this.isFull() && comin != null) {
            let minAccessCount:number = comin.accessCount;
            for (const value of this.cacheMap.values()) {
                if (value.accessCount == minAccessCount) {
                    cc.log(value.getValue())
                    cc.find('Canvas').removeChild(value.getValue())
                    value.getValue().decRef()
                    cc.assetManager.releaseAsset(value.getValue())
                    cc.log(value)
                    this.cacheMap.delete(value.getKey());
                    count++;
                }
            }
        }
        return count;
    }

}